package model

import (
	"fmt"
	"godobase/pkg/db"
	"log"

	"gorm.io/gorm"
)

func AutoMigrate() error {

	if err := db.DB.AutoMigrate(&User{}); err != nil {
		return fmt.Errorf("AutoMigrate for User failed: %v", err)
	}
	// 使用 GORM 的 CreateIndex 方法
	// createIndexIfNotExists(db.DB, &User{}, "username", "idx_user_username")
	// createIndexIfNotExists(db.DB, &User{}, "email", "idx_user_email")
	// createIndexIfNotExists(db.DB, &User{}, "phone", "idx_user_phone")
	if err := db.DB.AutoMigrate(&UserRole{}); err != nil {
		return fmt.Errorf("autoMigrate for UserRole failed: %v", err)
	}

	if err := db.DB.AutoMigrate(&UserDept{}); err != nil {
		return fmt.Errorf("autoMigrate for UserDept failed: %v", err)
	}

	if err := db.DB.AutoMigrate(&UserThird{}); err != nil {
		return fmt.Errorf("autoMigrate for UserThird failed: %v", err)
	}
	if err := EnsureDefaultUserRoleExists(); err != nil {
		log.Fatalf("初始化用户角色失败: %v", err)
	}
	if err := EnsureDefaultUserDeptExists(); err != nil {
		log.Fatalf("初始化部门失败: %v", err)
	}
	return nil
}
func CreateIndexIfNotExists(Db *gorm.DB, model interface{}, field, indexName string) {
	if db.AppConfig.DBType != "mongodb" {
		return
	}
	err := Db.Migrator().CreateIndex(model, indexName)
	if err != nil {
		log.Printf("Failed to create index %s for field %s: %v", indexName, field, err)
	}
}
